package de.Niklas.Laser.util.ConfigUtil;

import de.Niklas.Laser.LaserPlugin;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

public class ConfigGUI implements Listener {
    LaserPlugin plugin;
    public static String MAIN_TITLE;
    public static String BOOLEAN_TITLE;
    public static String INT_TITLE;
    public static String DOUBLE_TITLE;
    public static final String STRING_INVENTORY_TITLE;
    public static final String STRING_CRAFTING_LASER_TITLE;
    public static final String STRING_CRAFTING_AMMO_TITLE;
    public HashMap<String, String> stackTitles;

    static {
        ConfigGUI.MAIN_TITLE = ChatColor.BLUE + "Laser - Config Values:";
        ConfigGUI.BOOLEAN_TITLE = ChatColor.BLUE + "Laser - Change boolean value:";
        ConfigGUI.INT_TITLE = ChatColor.BLUE + "Laser - Change integer value:";
        ConfigGUI.DOUBLE_TITLE = ChatColor.BLUE + "Laser - Change double value:";
        STRING_INVENTORY_TITLE = ChatColor.translateAlternateColorCodes('&', "&aInsert blocks here:");
        STRING_CRAFTING_LASER_TITLE = ChatColor.translateAlternateColorCodes('&', "&aLaser - Insert blocks:");
        STRING_CRAFTING_AMMO_TITLE = ChatColor.translateAlternateColorCodes('&', "&aAmmo - Insert blocks:");
    }

    public ConfigGUI(final LaserPlugin plugin) throws IllegalArgumentException, IllegalAccessException {
        this.stackTitles = new HashMap<String, String>();
        this.plugin = plugin;
        Field[] declaredFields;
        for (int length = (declaredFields = Bundle.class.getDeclaredFields()).length, i = 0; i < length; ++i) {
            final Field f = declaredFields[i];
            final String s = ChatColor.stripColor(((ConfigSetting) f.get(null)).name);
            this.stackTitles.put(s.substring(0, s.length() - 1), f.getName());
        }
    }

    public static void openCompleteGUI(final Player p) throws IllegalArgumentException, IllegalAccessException {
        final Inventory PI = Bukkit.createInventory(null, 36, ConfigGUI.MAIN_TITLE);
        Field[] fields;
        for (int length = (fields = Bundle.class.getFields()).length, i = 0; i < length; ++i) {
            final Field f = fields[i];
            final ConfigSetting cs = (ConfigSetting) f.get(null);
            final ItemStack GUIStack = fastConstruct(cs.GUIStack.getType(), cs.GUIStack.getItemMeta().getDisplayName() + " " + ChatColor.GRAY + cs.getValue(), cs.GUIStack.getItemMeta().getLore());
            PI.addItem(GUIStack);
        }
        final ItemStack AmmoCraftingStack = fastConstruct(Material.WORKBENCH, ChatColor.YELLOW + "Ammo crafting:", ChatColor.DARK_GRAY + "The crafting recipe of the ammunition");
        final ItemStack LaserCraftingStack = fastConstruct(Material.WORKBENCH, ChatColor.YELLOW + "Laser crafting:", ChatColor.DARK_GRAY + "The crafting recipe of the laser");
        PI.addItem(AmmoCraftingStack, LaserCraftingStack);
        p.openInventory(PI);
    }

    public void openBooleanDialog(final Player p, final String fieldName, final boolean atm) {
        final Inventory PI = Bukkit.createInventory(null, 18, ConfigGUI.BOOLEAN_TITLE);
        PI.setItem(2, fastConstruct(Material.REDSTONE_BLOCK, ChatColor.RED + "Disable value", ChatColor.GRAY + "Set the value to false", ChatColor.GRAY + "..."));
        PI.setItem(6, fastConstruct(Material.EMERALD_BLOCK, ChatColor.GREEN + "Enable value", ChatColor.GRAY + "Set the value to true", ChatColor.GRAY + "..."));
        PI.setItem(17, fastConstruct(Material.BOOK, ChatColor.YELLOW + "Save value", ChatColor.GRAY + "Saves the value for", ChatColor.GRAY + fieldName, ChatColor.GRAY + "to " + atm));
        p.openInventory(PI);
    }

    public void openIntDialog(final Player p, final String fieldName, final int atm) {
        final Inventory PI = Bukkit.createInventory(null, 18, ConfigGUI.INT_TITLE);
        PI.setItem(0, fastConstruct(Material.GOLD_NUGGET, ChatColor.GOLD + "-1", ChatColor.GRAY + "Subtract 1 from the value"));
        PI.setItem(1, fastConstruct(Material.GOLD_INGOT, ChatColor.GOLD + "-5", ChatColor.GRAY + "Subtract 5 from the value"));
        PI.setItem(2, fastConstruct(Material.GOLD_BLOCK, ChatColor.GOLD + "-10", ChatColor.GRAY + "Subtract 10 from the value"));
        PI.setItem(3, fastConstruct(Material.PAPER, ChatColor.GRAY + "Value: " + ChatColor.YELLOW + atm));
        PI.setItem(6, fastConstruct(Material.GOLD_NUGGET, ChatColor.GOLD + "+1", ChatColor.GRAY + "Add 1 to the value"));
        PI.setItem(5, fastConstruct(Material.GOLD_INGOT, ChatColor.GOLD + "+5", ChatColor.GRAY + "Add 5 to the value"));
        PI.setItem(4, fastConstruct(Material.GOLD_BLOCK, ChatColor.GOLD + "+10", ChatColor.GRAY + "Add 10 to the value"));
        PI.setItem(17, fastConstruct(Material.BOOK, ChatColor.YELLOW + "Save value", ChatColor.GRAY + "Saves the value for", ChatColor.GRAY + fieldName, ChatColor.GRAY + "to " + atm));
        p.openInventory(PI);
    }

    public void openDoubleDialog(final Player p, final String fieldName, final double atm) {
        final Inventory PI = Bukkit.createInventory(null, 18, ConfigGUI.DOUBLE_TITLE);
        PI.setItem(0, fastConstruct(Material.GOLD_NUGGET, ChatColor.GOLD + "-0.1", ChatColor.GRAY + "Subtract 0.1 from the value"));
        PI.setItem(1, fastConstruct(Material.GOLD_INGOT, ChatColor.GOLD + "-1", ChatColor.GRAY + "Subtract 1 from the value"));
        PI.setItem(2, fastConstruct(Material.GOLD_BLOCK, ChatColor.GOLD + "-5", ChatColor.GRAY + "Subtract 5 from the value"));
        PI.setItem(3, fastConstruct(Material.PAPER, ChatColor.GRAY + "Value: " + ChatColor.YELLOW + atm));
        PI.setItem(6, fastConstruct(Material.GOLD_NUGGET, ChatColor.GOLD + "+0.1", ChatColor.GRAY + "Add 0.1 to the value"));
        PI.setItem(5, fastConstruct(Material.GOLD_INGOT, ChatColor.GOLD + "+1", ChatColor.GRAY + "Add 1 to the value"));
        PI.setItem(4, fastConstruct(Material.GOLD_BLOCK, ChatColor.GOLD + "+5", ChatColor.GRAY + "Add 5 to the value"));
        PI.setItem(17, fastConstruct(Material.BOOK, ChatColor.YELLOW + "Save value", ChatColor.GRAY + "Saves the value for", ChatColor.GRAY + fieldName, ChatColor.GRAY + "to " + atm));
        p.openInventory(PI);
    }

    @EventHandler
    public void onClick(final InventoryClickEvent e) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException {
        if (e.getInventory().getTitle().equalsIgnoreCase(ConfigGUI.MAIN_TITLE)) {
            e.setCancelled(true);
            final Player p = (Player) e.getWhoClicked();
            ItemStack is = null;
            String fieldName = "";
            try {
                is = e.getInventory().getItem(e.getRawSlot());
                if (is == null) {
                    throw new Exception();
                }
                fieldName = this.stackTitles.get(ChatColor.stripColor(is.getItemMeta().getDisplayName().split(":")[0]));
            } catch (Exception ex) {
                p.closeInventory();
            }
            if (fieldName != null && fieldName != "") {
                final String stackName = ChatColor.stripColor(is.getItemMeta().getDisplayName().split(":")[0]);
                final Field f = Bundle.class.getDeclaredField(fieldName);
                final Object o = ((ConfigSetting) f.get(null)).getValue();
                if (o.getClass().getName().equalsIgnoreCase("java.lang.Boolean")) {
                    this.plugin.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin, new Runnable() {
                        @Override
                        public void run() {
                            try {
                                ConfigGUI.this.openBooleanDialog(p, stackName, (boolean) o);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
                if (o.getClass().getName().equalsIgnoreCase("java.lang.Integer")) {
                    this.plugin.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin, new Runnable() {
                        @Override
                        public void run() {
                            try {
                                ConfigGUI.this.openIntDialog(p, stackName, (int) o);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
                if (o.getClass().getName().equalsIgnoreCase("java.lang.Double")) {
                    this.plugin.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin, new Runnable() {
                        @Override
                        public void run() {
                            try {
                                ConfigGUI.this.openDoubleDialog(p, stackName, (double) o);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
                if (fieldName.equalsIgnoreCase("OPTIONS_MATERIALS")) {
                    this.plugin.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin, new Runnable() {
                        @Override
                        public void run() {
                            try {
                                ConfigGUI.this.öffneMaterialInv(p);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            } else {
                String stackName = null;
                try {
                    stackName = ChatColor.stripColor(is.getItemMeta().getDisplayName().split(":")[0]);
                } catch (Exception ex2) {
                    return;
                }
                if (stackName != null && stackName != "") {
                    if (stackName.equalsIgnoreCase("Ammo crafting")) {
                        this.plugin.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin, new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    ConfigGUI.this.öffneAmmoCraftingInv(p);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                    if (stackName.equalsIgnoreCase("Laser crafting")) {
                        this.plugin.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin, new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    ConfigGUI.this.öffneLaserCraftingInv(p);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                }
            }
        }
        if (e.getInventory().getTitle().equalsIgnoreCase(ConfigGUI.BOOLEAN_TITLE)) {
            e.setCancelled(true);
            final Player p = (Player) e.getWhoClicked();
            ItemStack is = null;
            try {
                is = e.getInventory().getItem(e.getRawSlot());
            } catch (Exception ex3) {
                p.closeInventory();
            }
            if (is != null) {
                final String itemName = ChatColor.stripColor(is.getItemMeta().getDisplayName());
                if (itemName.equalsIgnoreCase("Disable value")) {
                    this.plugin.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin, new Runnable() {
                        @Override
                        public void run() {
                            try {
                                ConfigGUI.this.openBooleanDialog(p, ChatColor.stripColor(e.getInventory().getItem(17).getItemMeta().getLore().get(1)), false);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } else if (itemName.equalsIgnoreCase("Enable value")) {
                    this.plugin.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin, new Runnable() {
                        @Override
                        public void run() {
                            try {
                                ConfigGUI.this.openBooleanDialog(p, ChatColor.stripColor(e.getInventory().getItem(17).getItemMeta().getLore().get(1)), true);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } else if (itemName.equalsIgnoreCase("Save value")) {
                    final boolean saveValue = Boolean.valueOf(ChatColor.stripColor(e.getInventory().getItem(17).getItemMeta().getLore().get(2)).substring(3));
                    final String fieldName2 = this.stackTitles.get(ChatColor.stripColor(e.getInventory().getItem(17).getItemMeta().getLore().get(1)));
                    this.plugin.c.set(fieldName2.replace('_', '.').toLowerCase(), saveValue);
                    ((ConfigSetting) Bundle.class.getDeclaredField(fieldName2).get(null)).setValue(saveValue);
                    this.plugin.saveConfig();
                    this.plugin.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin, new Runnable() {
                        @Override
                        public void run() {
                            try {
                                ConfigGUI.openCompleteGUI(p);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
        }
        if (e.getInventory().getTitle().equalsIgnoreCase(ConfigGUI.INT_TITLE)) {
            e.setCancelled(true);
            final Player p = (Player) e.getWhoClicked();
            ItemStack is = null;
            try {
                is = e.getInventory().getItem(e.getRawSlot());
            } catch (Exception ex3) {
                p.closeInventory();
            }
            if (is != null) {
                final String itemName = ChatColor.stripColor(is.getItemMeta().getDisplayName());
                if (itemName.equalsIgnoreCase("-1") || itemName.equalsIgnoreCase("-5") || itemName.equalsIgnoreCase("-10") || itemName.equalsIgnoreCase("+10") || itemName.equalsIgnoreCase("+5") || itemName.equalsIgnoreCase("+1")) {
                    this.plugin.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin, new Runnable() {
                        @Override
                        public void run() {
                            try {
                                ConfigGUI.this.openIntDialog(p, ChatColor.stripColor(e.getInventory().getItem(17).getItemMeta().getLore().get(1)), Integer.valueOf(ChatColor.stripColor(e.getInventory().getItem(3).getItemMeta().getDisplayName()).substring(7)) + Integer.valueOf(itemName));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } else if (itemName.equalsIgnoreCase("Save value")) {
                    final int saveValue2 = Integer.valueOf(ChatColor.stripColor(e.getInventory().getItem(17).getItemMeta().getLore().get(2)).substring(3));
                    final String fieldName2 = this.stackTitles.get(ChatColor.stripColor(e.getInventory().getItem(17).getItemMeta().getLore().get(1)));
                    this.plugin.c.set(fieldName2.replace('_', '.').toLowerCase(), saveValue2);
                    ((ConfigSetting) Bundle.class.getDeclaredField(fieldName2).get(null)).setValue(saveValue2);
                    this.plugin.saveConfig();
                    this.plugin.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin, new Runnable() {
                        @Override
                        public void run() {
                            try {
                                ConfigGUI.openCompleteGUI(p);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
        }
        if (e.getInventory().getTitle().equalsIgnoreCase(ConfigGUI.DOUBLE_TITLE)) {
            e.setCancelled(true);
            final Player p = (Player) e.getWhoClicked();
            ItemStack is = null;
            try {
                is = e.getInventory().getItem(e.getRawSlot());
            } catch (Exception ex3) {
                p.closeInventory();
            }
            if (is != null) {
                final String itemName = ChatColor.stripColor(is.getItemMeta().getDisplayName());
                if (itemName.equalsIgnoreCase("-0.1") || itemName.equalsIgnoreCase("-1") || itemName.equalsIgnoreCase("-5") || itemName.equalsIgnoreCase("+5") || itemName.equalsIgnoreCase("+1") || itemName.equalsIgnoreCase("+0.1")) {
                    this.plugin.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin, new Runnable() {
                        @Override
                        public void run() {
                            try {
                                ConfigGUI.this.openDoubleDialog(p, ChatColor.stripColor(e.getInventory().getItem(17).getItemMeta().getLore().get(1)), Double.valueOf(ChatColor.stripColor(e.getInventory().getItem(3).getItemMeta().getDisplayName()).substring(7)) + Double.valueOf(itemName));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } else if (itemName.equalsIgnoreCase("Save value")) {
                    final double saveValue3 = Double.valueOf(ChatColor.stripColor(e.getInventory().getItem(17).getItemMeta().getLore().get(2)).substring(3));
                    final String fieldName3 = this.stackTitles.get(ChatColor.stripColor(e.getInventory().getItem(17).getItemMeta().getLore().get(1)));
                    this.plugin.c.set(fieldName3.replace('_', '.').toLowerCase(), saveValue3);
                    ((ConfigSetting) Bundle.class.getDeclaredField(fieldName3).get(null)).setValue(saveValue3);
                    this.plugin.saveConfig();
                    this.plugin.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin, new Runnable() {
                        @Override
                        public void run() {
                            try {
                                ConfigGUI.openCompleteGUI(p);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
        }
    }

    @EventHandler
    public void onCloseCustomInv(final InventoryCloseEvent e) {
        if (e.getInventory().getTitle().equalsIgnoreCase(ConfigGUI.STRING_INVENTORY_TITLE)) {
            final ArrayList<String> materialstrings = new ArrayList<String>();
            ItemStack[] contents;
            for (int length = (contents = e.getInventory().getContents()).length, i = 0; i < length; ++i) {
                final ItemStack is = contents[i];
                if (is != null) {
                    if (is.getType().isBlock()) {
                        materialstrings.add(is.getType().name());
                    }
                }
            }
            this.plugin.c.set("options.materials", materialstrings);
            this.plugin.saveConfig();
            Bundle.OPTIONS_MATERIALS.value = materialstrings;
            e.getPlayer().sendMessage(this.plugin.getLangString(LaserPlugin.Message.configValueGuiUpdated));
        }
        if (e.getInventory().getTitle().equalsIgnoreCase(ConfigGUI.STRING_CRAFTING_LASER_TITLE)) {
            final ArrayList<String> materialstrings = new ArrayList<String>();
            ItemStack[] contents2;
            for (int length2 = (contents2 = e.getInventory().getContents()).length, j = 0; j < length2; ++j) {
                final ItemStack is = contents2[j];
                if (is == null) {
                    materialstrings.add("AIR");
                } else {
                    materialstrings.add(is.getType().name());
                }
            }
            this.plugin.c.set("options.crafting", materialstrings);
            this.plugin.saveConfig();
            e.getPlayer().sendMessage(this.plugin.getLangString(LaserPlugin.Message.configValueGuiUpdated));
        }
        if (e.getInventory().getTitle().equalsIgnoreCase(ConfigGUI.STRING_CRAFTING_AMMO_TITLE)) {
            final ArrayList<String> materialstrings = new ArrayList<String>();
            ItemStack[] contents3;
            for (int length3 = (contents3 = e.getInventory().getContents()).length, k = 0; k < length3; ++k) {
                final ItemStack is = contents3[k];
                if (is == null) {
                    materialstrings.add("AIR");
                } else {
                    materialstrings.add(is.getType().name());
                }
            }
            this.plugin.c.set("options.ammocrafting", materialstrings);
            this.plugin.saveConfig();
            e.getPlayer().sendMessage(this.plugin.getLangString(LaserPlugin.Message.configValueGuiUpdated));
        }
    }

    private void öffneMaterialInv(final Player p) {
        final Inventory PI = Bukkit.createInventory(null, 54, ConfigGUI.STRING_INVENTORY_TITLE);
        final List<String> materials = this.plugin.c.getStringList("options.materials");
        for (final String s : materials) {
            PI.addItem(new ItemStack(Material.valueOf(s)));
        }
        p.openInventory(PI);
        p.updateInventory();
    }

    private void öffneLaserCraftingInv(final Player p) {
        final Inventory PI = Bukkit.createInventory(null, InventoryType.WORKBENCH, ConfigGUI.STRING_CRAFTING_LASER_TITLE);
        final List<String> materials = this.plugin.c.getStringList("options.crafting");
        for (int i = 1; i < 9; ++i) {
            try {
                if (materials.get(i) != "AIR") {
                    PI.setItem(i, new ItemStack(Material.valueOf(materials.get(i))));
                }
            } catch (Exception ex) {
            }
        }
        p.openInventory(PI);
    }

    private void öffneAmmoCraftingInv(final Player p) {
        final Inventory PI = Bukkit.createInventory(null, InventoryType.WORKBENCH, ConfigGUI.STRING_CRAFTING_AMMO_TITLE);
        final List<String> materials = this.plugin.c.getStringList("options.ammocrafting");
        for (int i = 1; i < 9; ++i) {
            try {
                if (materials.get(i) != "AIR") {
                    PI.setItem(i, new ItemStack(Material.valueOf(materials.get(i))));
                }
            } catch (Exception ex) {
            }
        }
        p.openInventory(PI);
    }

    public void runOneTaskLater(final Method m, final Object... args) {
        this.plugin.getServer().getScheduler().scheduleSyncDelayedTask(this.plugin, new Runnable() {
            @Override
            public void run() {
                try {
                    m.invoke(ConfigGUI.this.getInstance(), args);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public static ItemStack fastConstruct(final Material m, final String name, final String... lore) {
        return fastConstruct(m, name, Arrays.asList(lore));
    }

    public static ItemStack fastConstruct(final Material m, final String name, final List<String> lore) {
        final ItemStack is = new ItemStack(m);
        final ItemMeta im = is.getItemMeta();
        im.setDisplayName(name);
        im.setLore(lore);
        is.setItemMeta(im);
        return is;
    }

    public ConfigGUI getInstance() {
        return this;
    }
}
